package com.conversationboard.model;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;
import com.conversationboard.model.propertybag.Property;
import com.conversationboard.model.propertybag.PropertyBag;
import com.conversationboard.serialisation.XmlSerialiser;

public class PendingRegistrations extends ArrayList<PendingRegistration> {

	private static final long serialVersionUID = -3101327033870685451L;


	public static PendingRegistrations getInstance() throws SQLException {

		Property property = PropertyBag.get("pendingregistrations");

		PendingRegistrations pendingRegistrations = null;

		if (property == null) {
			pendingRegistrations = new PendingRegistrations();
		} else {
			XmlSerialiser serialiser = new XmlSerialiser();
			serialiser.setAlias("PendingRegistrations", PendingRegistrations.class);
			serialiser.setAlias("PendingRegistration", PendingRegistration.class);
			serialiser.setAlias("TimeZone", TimeZone.class);
			pendingRegistrations = (PendingRegistrations) serialiser.deSerialise(property.getValue());
		}

		return pendingRegistrations;

	}


	public void store() throws SQLException {

		XmlSerialiser serialiser = new XmlSerialiser();
		serialiser.setAlias("PendingRegistrations", PendingRegistrations.class);
		serialiser.setAlias("PendingRegistration", PendingRegistration.class);
		serialiser.setAlias("TimeZone", TimeZone.class);

		String xml = serialiser.serialise(this);

		PropertyBag.put("pendingregistrations", xml);

	}


	public static List<String> getUsersWithSamePassword(String password) throws SQLException, UnsupportedEncodingException {

		Connection connection = null;

		List<String> usersWithSamePassword = new LinkedList<String>();

		try {

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.GET_USERS_WITH_SAME_PASSWORD);

			statement.setString(1, password);
			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			while (resultSet.next()) {
				usersWithSamePassword.add(resultSet.getString("displayname"));
			}

			return usersWithSamePassword;

		} finally {
			Database.close(connection);
		}

	}
}
